package com.ljx.designMode.agency;


import lombok.AllArgsConstructor;
import lombok.Data;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author LJX
 * @Description: TODO
 * @Date: 2022/11/9 14:34
 * @Version 1.0
 */
@Data
@AllArgsConstructor
public class CglibDynaminAgencyTest {
	public static void main(String[] args) {
		ProxyFactory1 proxyFactory1 = new ProxyFactory1(new Star2());
		YanYuan instance = proxyFactory1.getInstance();
		System.out.println(instance);
//		instance.movie();

	}
}

interface YanYuan{
	void movie();
}

class Star2 implements YanYuan{
	@Override
	public void movie() {
		System.out.println("彭于晏演电影");
	}
}

class ProxyFactory1 implements MethodInterceptor{
	// 被代理的对象
	private Object target;

	public ProxyFactory1(Object target) {
		this.target = target;
	}

	// 获取代理对象
	public YanYuan getInstance(){
		// 创建一个工具--生成代理类对对象
		Enhancer enhancer = new Enhancer();
		// 指定被代理的父类
		enhancer.setSuperclass(target.getClass());
		// 代理的回调方法
		enhancer.setCallback(this);
		return (YanYuan) enhancer.create();
	}

	// 执行被代理类的方法时会执行该方法
	@Override
	public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
		sing();
		Object invoke = method.invoke(target, objects);
		dance();
		return invoke;
	}

	public void sing(){
		System.out.println("唱歌");
	}
	public void dance(){
		System.out.println("跳舞");
	}
}